package com.xyz.bigcorn.admin.common.shiro;

import com.xyz.bigcorn.admin.system.entity.Authority;
import com.xyz.bigcorn.admin.system.entity.Role;
import com.xyz.bigcorn.admin.system.entity.User;
import com.xyz.bigcorn.admin.system.service.AuthorityService;
import com.xyz.bigcorn.admin.system.service.RoleService;
import com.xyz.bigcorn.admin.system.service.UserService;
import com.xyz.bigcorn.admin.utils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: 自定义realm
 * @author: Zhaopengfei
 * @copyright: 金鹏信息技术有限公司
 * @CreatedDate: 2018年04月12日 16:08
 * @Copyright: All rights Reserved，Designed By Jpsycn
 */
public class UserRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(UserRealm.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthorityService authorityService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
//        String username = (String)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 角色
        List<Role> userRoles = roleService.getByUserId(user.getId());
        Set<String> roles = new HashSet<>();
        for (int i = 0; i < userRoles.size(); i++) {
            roles.add(String.valueOf(userRoles.get(i).getId()));
        }
        authorizationInfo.setRoles(roles);
        // 权限
        List<Authority> authorities = authorityService.listByUserId(user.getId());
        Set<String> permissions = new HashSet<>();
        for (int i = 0; i < authorities.size(); i++) {
            String authority = authorities.get(i).getPermission();
            if (StringUtil.isNotBlank(authority)) {
                permissions.add(authority);
            }
        }
        authorizationInfo.setStringPermissions(permissions);
        System.out.println(permissions);
        return authorizationInfo;

    }
    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        logger.info("验证当前Subject时获取到token为：" + token.toString());
        String username = (String) authenticationToken.getPrincipal();
        User user = userService.getByUsername(username);
        if (user == null) {
            throw new UnknownAccountException(); // 账号不存在
        }
        if (!user.getStatus().equals( "0")) {
            throw new LockedAccountException();  // 账号被锁定
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getUserName()+user.getSalt()), getName());
        return authenticationInfo;
    }


    public static void main(String[] args) {
        String hashAlgorithmName = "MD5";//加密方式
        Object crdentials = "123456";//密码原值
        Object salt = "adminjpxx";//盐值
        int hashIterations = 1024;//加密1024次
        Object result = new SimpleHash(hashAlgorithmName,crdentials,salt,hashIterations);
        System.out.println(result);

        System.err.println("经过加密以后的密码是："+result);//00e4595eafdabb56b49cbf810aadd5aa
    }
}
